<?php

namespace App\Repository\Repositories;

use Illuminate\Support\Facades\DB;
use Exception;
use App\Repository\Models\Products;
use App\Repository\Repositories\Interfaces\ProductsRepository;

/**
 * Class ProductsRepositoryEloquent.
 *
 * @package namespace App\Repository\Repositories;
 */
class ProductsRepositoryEloquent extends BaseRepository implements ProductsRepository
{
    /**
     * 搜索
     * @var array
     */
    protected $fieldSearchable = [
        'id',
        'status',
        'product_type',
        'is_for_sale',
		'name'=> 'like',
        'brand_id',

        'is_index_recommend',
        'first_cat',
        'second_cat',
        'third_cat',
        'custom_cate',
		'shop.sp_name' => 'like',
		'attrs.attributes' => 'like',
        'skus.price' => 'between',

        'is_cupboard',
        'shop_id'=>'in',
        'user_id',
        'created_at' => 'between',
        'updated_at' => 'between',

    ];

	 public $fieldSearchReplace = [
        'attrs_attributes' => 'attrs.attributes',
        'sp_name' => 'shop.sp_name',
        'price' => 'skus.price',
        'goods_id'=>'id',
        'goods_name'=>'name',

    ];

	 
	 /**
	  * 可关联查询的字段
	  */
	 public $withAllow = [
	     'skus'=> ['product_id', 'price', 'sale_price','sku_code','id'],
	     'shop',
	     'attrs'
	 ];

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Products::class;
    }

    public function batchDelete($ids){
        return $this->model->whereIn('id',$ids)->delete();
    }
    
    public function batchSale($data){
        return $this->model->whereIn('id',$data['ids'])->update( ['is_for_sale'=>$data['is_sale']] );
    }
    
    public function batchStatus($data){
        return $this->model->whereIn('id',$data['ids'])->update( ['status'=>$data['status']] );
    }
    
    public function createNew($data)
    {
        $skus = isset($data['skus']) && $data['skus'] ? $data['skus'] : "";
        if($skus){
            unset($data['skus']);
        }
        DB::beginTransaction();
        try {
            $model = $this->model->newInstance($data);
            $model->save();
            $products = $model->toArray();
            if($skus){
                $skus= json_decode($skus,true);
                foreach($skus as &$sku){
                    
                    if(!isset($sku['price']) || !$sku['price']){
                        $sku['price'] = 0;
                    } 
                    $sku['sku_code'] = 'v'.date("Ymd").$products['id'].rand(10000,100000);
                }
                $model->skus()->createMany($skus);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback(); //事务回滚;
            return [];
        }
        
        $ret['data']=$products;
        return $ret;
    }
    
    
    //资质发布
    public function createNewZZ($data)
    {
        $attrs = isset($data['pattrs']) && $data['pattrs'] ? $data['pattrs'] : "";
        $price = isset($data['price']) && $data['price'] ? $data['price'] : 0;
        if($attrs){
            unset($data['pattrs']);
        }
        DB::beginTransaction();
        try {
            $model = $this->model->newInstance($data);
            $model->save();
            $products = $model->toArray();
            if($attrs){
                $attr_data['attributes']= $attrs;
                $attr_data['product_id'] = $products['id'];
                $attr_data['price'] = $price;
                $model->attrs()->create($attr_data);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback(); //事务回滚;
            return [];
        }
      
        $ret['data']=$products;
        return $ret;
    }
    
    

    public function incrementCommentCount($product_id, $comment_score)
    {
        $this->model->where('id', $product_id)->increment('comment_count', 1);
        $this->model->where('id', $product_id)->increment('comment_score', $comment_score);
    }
    
    public function cupboardCount($shop_id,$value=1,$proudct_type=1){
        $ret = $this->findWhere(['shop_id' => $shop_id, 'is_cupboard' => $value,'product_type'=>$proudct_type]);
        return $ret ;
    }

    /**
     * @TODO 首页推荐商品设置
     * */
    public function setRecommend($id,$status=0,$sort=2){

        try {
            if ($status==1) {
                // 获取当前产品的 一级分类。
                $proInfo = $this->model->where('id', $id)->get()->toArray();
                if (isset($proInfo[0])) {
                    $first_cat = $proInfo[0]['first_cat'];
                    // 获取该分类下的 已推荐到首页的商品数量
                    $countRec = $this->model->where(['first_cat' => $first_cat, 'is_index_recommend'=>1])->get()->toArray();
                    $ids = array_column($countRec,'id');
                    if (count($countRec)>=4&&!in_array($id,$ids)){ // 检测本id是否为已推荐的。如果原本是已推荐，即继续执行更新操作。
                        $info = '该一级分类下商品推荐数量已达到上限';
                        $return['info'] = $info;
                        throw  new \Exception($info);
                    }
                }
            }
            $update = $this->query()->where('id', $id)->update(['is_index_recommend' => $status,'index_sort'=>$sort]);
        }catch (\Exception $e){
            return ['flag'=>false,'info'=>$e->getMessage()];
        }
        return ['flag'=>true,'info'=>'修改成功'];

    }

}
